package com.gome.ocean.common.utils;

import java.sql.SQLSyntaxErrorException;
import java.util.List;

import com.alibaba.cobar.parser.ast.stmt.SQLStatement;
import com.alibaba.cobar.parser.recognizer.SQLParserDelegate;
import com.alibaba.druid.sql.SQLUtils;
import com.gome.ocean.common.enums.DataBaseType;
import com.taobao.tddl.optimizer.exception.SqlParserException;
import com.taobao.tddl.optimizer.parse.cobar.CobarSqlAnalysisResult;
import com.taobao.tddl.optimizer.parse.cobar.visitor.MysqlParameterizedSqlVistor;

/**
 * GDDL解析
 * 
 * @author haqiaolong 2016年10月10日 上午10:46:35
 * @since 5.0.0
 */
public final class GddlParseHelper {

	public static com.alibaba.druid.sql.ast.SQLStatement parseStatement(final String sql,final DataBaseType dataBaseType){
		List<com.alibaba.druid.sql.ast.SQLStatement> sqlStatement = SQLUtils.parseStatements(sql, dataBaseType.getTypeFullName());
		return sqlStatement.get(0);
	}
	
    /**
     * 检测解析
     * 
     * @param sql
     * @param cached
     * @return
     * @throws SqlParserException
     */
    public static SQLStatement parseStatement(final String sql, final ParserResult parserResult)
                                                                                                throws SqlParserException {
        CobarSqlAnalysisResult result = new CobarSqlAnalysisResult();
        result.build(sql, parserResult.parameterizedSql, parserResult.index, parserResult.statement);
        SQLStatement sqlStatement = result.getStatement();
        return sqlStatement;
    }

    public static ParserResult parseSql(String sql) throws SQLSyntaxErrorException {
        ParserResult result = new ParserResult();
        SQLStatement statement = SQLParserDelegate.parse(sql);
        result.statement = statement;

        StringBuilder appendable = new StringBuilder();
        MysqlParameterizedSqlVistor visitor = new MysqlParameterizedSqlVistor(appendable, true);
        statement.accept(visitor);
        result.parameterizedSql = visitor.getSql();
        return result;
    }
}
